<template>
  <view class="container">
    <!-- 标题栏 - 保持基础层级，确保模态框能覆盖 -->
    <uni-nav-bar 
      dark 
      :fixed="true" 
      shadow 
      status-bar 
      left-icon="arrow-left" 
      right-icon="refreshempty" 
      title="客户欠费（元）" 
      @clickLeft="back" 
      @clickRight="sx()"
      class="nav-bar"
    />
    
    <view class="main-content">
      <view class="search-container">
        <view class="search-filter-row">
          <view class="search-box">
            <uni-icons type="search" size="18" color="#999" class="search-icon"></uni-icons>
            <input 
              type="text" 
              v-model="filterParams.customerName" 
              placeholder="请输入客户名称搜索"
              class="search-input"
              @confirm="handleQuery"
              @input="initPage(1)"
            />
          </view>
          
          <view class="filter-text-btn" @click="toggleFilterPanel">
            <text>筛选</text>
            <uni-icons 
              type="arrow-down" 
              size="16" 
              color="#333"
              :class="isFilterOpen ? 'rotate-up' : ''"
              class="filter-icon"
            ></uni-icons>
          </view>
        </view>
        
        <!-- 筛选面板 - 作为页面内元素，不使用遮罩，层级正常 -->
        <view class="filter-panel" v-if="isFilterOpen">
          <view class="filter-item">
            <text class="filter-label">合计：</text>
            <view class="amount-range">
              <input 
                type="number" 
                v-model="filterParams.minAmount" 
                placeholder="最小金额"
                class="amount-input"
                @input="handleInputFilter('minAmount')"
                @blur="checkAmountRange"
              />
              <text class="range-separator">~</text>
              <input 
                type="number" 
                v-model="filterParams.maxAmount" 
                placeholder="最大金额"
                class="amount-input"
                @input="handleInputFilter('maxAmount')"
                @blur="checkAmountRange"
              />
              <text class="amount-unit">元</text>
              <button class="confirm-btn" @click="handleQuery">确认筛选</button>
            </view>
          </view>
          
          <view class="amount-presets">
            <view 
              class="preset-item" 
              :class="{selected: selectedAmount === 10000}" 
              @click="setPresetAmount(10000)"
            >
              1万元
            </view>
            <view 
              class="preset-item" 
              :class="{selected: selectedAmount === 100000}" 
              @click="setPresetAmount(100000)"
            >
              10万元
            </view>
            <view 
              class="preset-item" 
              :class="{selected: selectedAmount === 500000}" 
              @click="setPresetAmount(500000)"
            >
              50万元
            </view>
            <view 
              class="preset-item" 
              :class="{selected: selectedAmount === 1000000}" 
              @click="setPresetAmount(1000000)"
            >
              100万元
            </view>
            <view 
              class="preset-item" 
              :class="{selected: selectedAmount === 5000000}" 
              @click="setPresetAmount(5000000)"
            >
              500万元
            </view>
            <view 
              class="preset-item" 
              :class="{selected: selectedAmount === 10000000}" 
              @click="setPresetAmount(10000000)"
            >
              1000万元
            </view>
            <view 
              class="preset-item other-item" 
              :class="{selected: selectedAmount === 'other'}" 
              @click="showOtherAmountInput"
            >
              其它
            </view>
          </view>
        </view>
      </view>

      <scroll-view 
        class="table-scroll-container"
        scroll-x="true"
        scroll-y="true"
        :style="{ height: tableHeight }"
        @scrolltolower="handleLoadMore"
      >
        <!-- 表格内容 -->
        <view class="data-table" :style="{ width: totalTableWidth + 'px' }">
          <view class="table-header table-header-fixed">
            <view class="table-cell cell-city table-col-fixed-1" @click="handleSort('khName')">
              <view class="header-content">
                <div class="header-text">客户名称</div>
                <div class="sort-icon-container">
                  <view class="sort-icon-group">
                    <text class="sort-icon up-icon" :style="{color: sortConfig.key === 'khName' && sortConfig.type === 'asc' ? '#ff0101' : '#999'}">▲</text>
                    <text class="sort-icon down-icon" :style="{color: sortConfig.key === 'khName' && sortConfig.type === 'desc' ? '#ff0101' : '#999'}">▼</text>
                  </view>
                </div>
              </view>
            </view>
            
            <view class="table-cell cell-data" :style="{ width: deptColumnWidth + 'px' }" @click="handleSort('jgName')">
              <view class="header-content">
                <div class="header-text">所属单位</div>
                <div class="sort-icon-container">
                  <view class="sort-icon-group">
                    <text class="sort-icon up-icon" :style="{color: sortConfig.key === 'jgName' && sortConfig.type === 'asc' ? '#ff0101' : '#999'}">▲</text>
                    <text class="sort-icon down-icon" :style="{color: sortConfig.key === 'jgName' && sortConfig.type === 'desc' ? '#ff0101' : '#999'}">▼</text>
                  </view>
                </div>
              </view>
            </view>
            
            <view class="table-cell cell-data cell-content-center slide-column" :style="{ width: majorColumnWidth + 'px' }" @click="handleSort('dataSource')">
              <view class="header-content">
                <div class="header-text">所属专业</div>
                <div class="sort-icon-container">
                  <view class="sort-icon-group">
                    <text class="sort-icon up-icon" :style="{color: sortConfig.key === 'dataSource' && sortConfig.type === 'asc' ? '#ff0101' : '#999'}">▲</text>
                    <text class="sort-icon down-icon" :style="{color: sortConfig.key === 'dataSource' && sortConfig.type === 'desc' ? '#ff0101' : '#999'}">▼</text>
                  </view>
                </div>
              </view>
            </view>

            <view class="table-cell cell-data cell-content-center" :style="{ width: currentPeriodColumnWidth + 'px' }" @click="handleSort('qnqf')">
              <view class="header-content">
                <div class="header-text">期内欠费</div>
                <div class="sort-icon-container">
                  <view class="sort-icon-group">
                    <text class="sort-icon up-icon" :style="{color: sortConfig.key === 'qnqf' && sortConfig.type === 'asc' ? '#ff0101' : '#999'}">▲</text>
                    <text class="sort-icon down-icon" :style="{color: sortConfig.key === 'qnqf' && sortConfig.type === 'desc' ? '#ff0101' : '#999'}">▼</text>
                  </view>
                </div>
              </view>
            </view>
            
            <view class="table-cell cell-data cell-content-center" :style="{ width: overdueColumnWidth + 'px' }" @click="handleSort('yqqf')">
              <view class="header-content">
                <div class="header-text">逾期欠费</div>
                <div class="sort-icon-container">
                  <view class="sort-icon-group">
                    <text class="sort-icon up-icon" :style="{color: sortConfig.key === 'yqqf' && sortConfig.type === 'asc' ? '#ff0101' : '#999'}">▲</text>
                    <text class="sort-icon down-icon" :style="{color: sortConfig.key === 'yqqf' && sortConfig.type === 'desc' ? '#ff0101' : '#999'}">▼</text>
                  </view>
                </div>
              </view>
            </view>
            
            <view class="table-cell cell-data cell-content-center" :style="{ width: amountColumnWidth + 'px' }" @click="handleSort('hj')">
              <view class="header-content">
                <div class="header-text">合计</div>
                <div class="sort-icon-container">
                  <view class="sort-icon-group">
                    <text class="sort-icon up-icon" :style="{color: sortConfig.key === 'hj' && sortConfig.type === 'asc' ? '#ff0101' : '#999'}">▲</text>
                    <text class="sort-icon down-icon" :style="{color: sortConfig.key === 'hj' && sortConfig.type === 'desc' ? '#ff0101' : '#999'}">▼</text>
                  </view>
                </div>
              </view>
            </view>
          </view>
          
          <view class="table-body">
            <view 
              class="table-row" 
              v-for="(item, index) in sortedTableData" 
              :key="'data-' + index + item.khCode + item.rq"
              :class="index % 2 === 0 ? 'row-even' : 'row-odd'"
            >
              <view class="table-cell cell-city table-col-fixed-1 customer-name">
                <text 
                  class="customer-name-link"
                  @click="handleGoToDetail(item)"
                >
                  {{ item.khName }}
                </text>
              </view>
              
              <view class="table-cell cell-data" :style="{ width: deptColumnWidth + 'px' }">
                {{ formatUnitName(item.jgName || '' )}}
              </view>
              
              <view class="table-cell cell-data cell-content-center slide-column" :style="{ width: majorColumnWidth + 'px' }">
				{{ formatUnitName(item.zy || '' )}}
              </view>

              <view class="table-cell cell-data cell-content-center" :style="{ width: currentPeriodColumnWidth + 'px' }">
                {{ formatToWan(item.qnqf) }}
              </view>
              
              <view class="table-cell cell-data cell-content-center overdue-column" :style="{ width: overdueColumnWidth + 'px' }">
                <text class="overdue-text">{{ formatToWan(item.yqqf) }}</text>
              </view>
              
              <view class="table-cell cell-data cell-content-center" :style="{ width: amountColumnWidth + 'px' }">
                {{ formatToWan(item.hj) }}
              </view>
            </view>
            
            <view 
              class="table-row empty-row" 
              v-for="index in emptyRowCount" 
              :key="'empty-' + index"
              :class="(sortedTableData.length + index) % 2 === 0 ? 'row-even' : 'row-odd'"
            >
              <view class="table-cell cell-city table-col-fixed-1"></view>
              <view class="table-cell cell-data" :style="{ width: deptColumnWidth + 'px' }"></view>
              <view class="table-cell cell-data cell-content-center slide-column" :style="{ width: majorColumnWidth + 'px' }"></view>
              <view class="table-cell cell-data cell-content-center" :style="{ width: currentPeriodColumnWidth + 'px' }"></view>
              <view class="table-cell cell-data cell-content-center" :style="{ width: overdueColumnWidth + 'px' }"></view>
              <view class="table-cell cell-data cell-content-center" :style="{ width: amountColumnWidth + 'px' }"></view>
            </view>
          </view>
        </view>
        
        <view v-if="isLoadingMore" class="loading-tip">
          <uni-loading-icon type="circle" size="24"></uni-loading-icon>
          <text class="loading-text">加载中...</text>
        </view>
        
        <view v-if="showNoMoreTip && !hideNoMoreTip" class="loading-tip" :class="{fadeOut: startFadeOut}">
          <text>已加载全部数据</text>
        </view>
      </scroll-view>
      
      <view class="pagination-info">
        <text>第 <text style="color: red; font-weight: bold;">{{ currentPage }}</text> 页 / 共 <text style="color: red; font-weight: bold;">{{ pageInfo.pageTotal || 0 }}</text> 页</text>
        <text style="margin: 0 8px; color: #ccc;">|</text>
        <text>已展示 <text style="color: red; font-weight: bold;">{{ sortedTableData.length }}</text> 条 / 共 <text style="color: red; font-weight: bold;">{{ pageInfo.total || 0 }}</text> 条</text>
      </view>
    </view>
  </view>
</template>

<script>
import utils from '../../common/utils'

export default {
  data() {
    return {
      tableData: [],
      currentPage: 1,
      pageInfo: {
        total: 0,
        pageTotal: 0,
        pageSize: 10
      },
      total: { HJ: '', YQQF: '' },
      sortConfig: {
        key: '',
        type: 'asc'
      },
      minRowCount: 10,
      tableHeight: '600px',
      filterParams: {
        customerName: '',
        minAmount: '0',
        maxAmount: '10000000'
      },
      applyFilter: false,
      isFilterOpen: false,
      fixedColWidth: 130,
      deptColumnWidth: 115,
      majorColumnWidth: 95,
      currentPeriodColumnWidth: 90,
      overdueColumnWidth: 95,
      amountColumnWidth: 90,
      totalTableWidth: 0,
      pagePadding: 20,
      isLoadingMore: false,
      hasMoreData: true,
      hideNoMoreTip: false,
      startFadeOut: false,
      noMoreTimer: null,
      selectedAmount: 10000000 // 默认选中1000万元
    };
  },
  computed: {
    sortedTableData() {
      let data = [...this.tableData];
      
      if (this.filterParams.customerName.trim()) {
        const keyword = this.filterParams.customerName.trim().toLowerCase();
        data = data.filter(item => {
          return item.khName?.toLowerCase().includes(keyword) || false;
        });
      }
      
      if (this.applyFilter) {
        const minAmt = this.filterParams.minAmount ? Number(this.filterParams.minAmount) : 0;
        const maxAmt = this.filterParams.maxAmount ? Number(this.filterParams.maxAmount) : Infinity;
        
        if (!isNaN(minAmt) && !isNaN(maxAmt) && minAmt <= maxAmt) {
          data = data.filter(item => {
            const hj = Number(item.hj) || 0;
            return hj >= minAmt && hj <= maxAmt;
          });
        }
      }
      
      if (this.sortConfig.key) {
        data = data.sort((a, b) => {
          const valueA = a[this.sortConfig.key];
          const valueB = b[this.sortConfig.key];
          
          if (typeof valueA === 'number' && typeof valueB === 'number') {
            return this.sortConfig.type === 'asc' ? valueA - valueB : valueB - valueA;
          }
          
          if (typeof valueA === 'string' && typeof valueB === 'string') {
            const compare = valueA.localeCompare(valueB, 'zh-CN');
            return this.sortConfig.type === 'asc' ? compare : -compare;
          }
          
          return 0;
        });
      }
      
      return data;
    },
    emptyRowCount() {
      const need = this.minRowCount - this.sortedTableData.length;
      return need > 0 ? need : 0;
    },
    showNoMoreTip() {
      return !this.hasMoreData && 
             this.pageInfo.total > 0 && 
             !this.isLoadingMore && 
             this.tableData.length >= this.pageInfo.pageSize;
    }
  },
  watch: {
    showNoMoreTip(newVal) {
      if (this.noMoreTimer) {
        clearTimeout(this.noMoreTimer);
        this.noMoreTimer = null;
      }
      
      if (newVal) {
        this.hideNoMoreTip = false;
        this.startFadeOut = false;
        
        this.noMoreTimer = setTimeout(() => {
          this.startFadeOut = true;
          
          setTimeout(() => {
            this.hideNoMoreTip = true;
          }, 500);
        }, 1500);
      } else {
        this.hideNoMoreTip = true;
        this.startFadeOut = false;
      }
    }
  },
  onLoad(options) {
    console.info("接收请求参数：", JSON.stringify(options));
    if (options) {
      this.filterParams.customerName = decodeURIComponent(options.customerName || '');
    } else {
      console.error("未获取到请求参数");
    }
    this.calculateTableLayout();
    uni.onWindowResize(this.calculateTableLayout);
  },
  onUnload() {
    uni.offWindowResize(this.calculateTableLayout);
    if (this.noMoreTimer) {
      clearTimeout(this.noMoreTimer);
    }
  },
  onShow() {
    if (this.tableData.length === 0) {
      this.hasMoreData = true;
      this.initPage(this.currentPage);
    }
  },
  methods: {
    formatToWan(num) {
      return num;
    },  
    back() {
      uni.switchTab({
        url: '/pages/index/index',
        fail: (err) => {
          uni.redirectTo({
            url: '/pages/index/index',
            fail: (err2) => {
              console.error('跳转index页面失败：', err2);
              this.handleBack();
            }
          });
        }
      });
    },
	sx() {
	  // 1. 重置筛选核心标志
	  this.applyFilter = false;
	
	  // 2. 还原金额范围参数（初始值）
	  this.filterParams.minAmount = '0'; // 初始最小金额
	  this.filterParams.maxAmount = '10000000'; // 初始最大金额（1000万元）
	
	  // 3. 还原预设金额选中状态（默认选中1000万元）
	  this.selectedAmount = 10000000;
	
	  // 4. 关闭筛选面板
	  this.isFilterOpen = false;
	
	  // 5. 重置分页与数据（确保重新加载第一页）
	  this.currentPage = 1; // 页码重置为1
	  this.tableData = []; // 清空现有数据
	  this.hasMoreData = true; // 允许重新加载更多
	  this.isLoadingMore = false; // 重置加载状态
	
	  // 6. 重新加载第一页数据
	  this.initPage(1);
	},
    handleSort(key) {
      if (this.sortConfig.key === key) {
        this.sortConfig.type = this.sortConfig.type === 'asc' ? 'desc' : 'asc';
      } else {
        this.sortConfig.key = key;
        this.sortConfig.type = 'asc';
      }
    },
    calculateTableLayout() {
      try {
        const { windowHeight, windowWidth, statusBarHeight } = uni.getSystemInfoSync();
        const navHeight = 44 + statusBarHeight; // 标题栏总高度（含状态栏）
        const searchHeight = this.isFilterOpen ? 300 : 80; // 筛选区域高度（展开/收起）
        const paginationHeight = 50; // 分页信息高度

        // 计算表格高度（窗口高度 - 标题栏 - 筛选区 - 分页区）
        this.tableHeight = `${windowHeight - navHeight - searchHeight - paginationHeight}px`;

        const availableWidth = windowWidth - this.fixedColWidth - this.pagePadding - 20;
        
        if (availableWidth > 0) {
          if (windowWidth > 450) {
            this.deptColumnWidth = Math.max(Math.floor(availableWidth * 0.25), 110);
            this.majorColumnWidth = Math.max(Math.floor(availableWidth * 0.20), 100);
            this.currentPeriodColumnWidth = Math.max(Math.floor(availableWidth * 0.18), 90);
            this.overdueColumnWidth = Math.max(Math.floor(availableWidth * 0.18), 90);
            this.amountColumnWidth = Math.max(Math.floor(availableWidth * 0.18), 90);
          } else {
            this.deptColumnWidth = Math.max(Math.floor(availableWidth * 0.22), 100);
            this.majorColumnWidth = Math.max(Math.floor(availableWidth * 0.22), 100);
            this.currentPeriodColumnWidth = Math.max(Math.floor(availableWidth * 0.19), 85);
            this.overdueColumnWidth = Math.max(Math.floor(availableWidth * 0.19), 85);
            this.amountColumnWidth = Math.max(Math.floor(availableWidth * 0.18), 85);
          }
        }
        
        this.totalTableWidth = this.fixedColWidth + this.deptColumnWidth + this.majorColumnWidth + 
                              this.currentPeriodColumnWidth + this.overdueColumnWidth + this.amountColumnWidth;
      } catch (e) {
        console.error('计算表格布局失败:', e);
        this.tableHeight = '500px';
        this.deptColumnWidth = 115;
        this.majorColumnWidth = 95;
        this.currentPeriodColumnWidth = 90;
        this.overdueColumnWidth = 95;
        this.amountColumnWidth = 90;
        this.totalTableWidth = this.fixedColWidth + 115 + 95 + 90 + 95 + 90;
      }
    },
    toggleFilterPanel() {
      this.isFilterOpen = !this.isFilterOpen;
      this.calculateTableLayout(); // 切换时重新计算表格高度
    },
    handleInputFilter(type) {
      const value = this.filterParams[type];
      if (type === 'minAmount' || type === 'maxAmount') {
        let processed = value.replace(/[^-\d.]/g, '');
        const minusCount = processed.split('-').length - 1;
        if (minusCount > 1) {
          processed = '-' + processed.replace(/-/g, '');
        }
        processed = processed.replace(/\.{2,}/g, '.');
        if (processed.startsWith('.')) {
          processed = '0' + processed;
        }
        if (processed.startsWith('-.') && processed.length > 1) {
          processed = '-0.' + processed.slice(2);
        }
        this.filterParams[type] = processed;
      } else if (type === 'customerName') {
        this.filterParams[type] = value.replace(/[\<\>\*\?\\\/]/g, '');
      }
    },
    checkAmountRange() {
      const min = this.filterParams.minAmount ? Number(this.filterParams.minAmount) : 0;
      const max = this.filterParams.maxAmount ? Number(this.filterParams.maxAmount) : Infinity;
      if (!isNaN(min) && !isNaN(max) && min > max) {
        this.$utils.toast('最小金额不能大于最大金额，请重新输入');
      }
    },
    handleQuery() {
      this.applyFilter = true;
      this.hasMoreData = true;
      this.isLoadingMore = false;
      this.currentPage = 1;
      this.tableData = [];
      this.initPage(this.currentPage).then(() => {
        this.isFilterOpen = false;
        this.calculateTableLayout();
      });
    },
    handleLoadMore() {
      if (this.isLoadingMore || !this.hasMoreData) {
        return;
      }
      
      if (this.currentPage >= this.pageInfo.pageTotal) {
        this.hasMoreData = false;
        return;
      }
      
      this.isLoadingMore = true;
      this.currentPage += 1;
      this.initPage(this.currentPage).then(() => {
        this.isLoadingMore = false;
        this.hasMoreData = this.currentPage < this.pageInfo.pageTotal;
      }).catch(() => {
        this.currentPage -= 1;
        this.isLoadingMore = false;
      });
    },
    initPage: async function (pageNum) {
      if (pageNum === 1) {
        this.$utils.showLoading("数据加载中...");
      }
      
      try {
        const timestamp = this.$utils.getTimestamp();
        const userInfo = uni.getStorageSync("userInfo");
        
        const enData = this.$utils.encrypt(
          JSON.stringify({ 
            timestamp,
            curpage: pageNum,
            pagesize: 30,
            cxmc: this.filterParams.customerName.trim(),
            zxhj: this.applyFilter ? (this.filterParams.minAmount ? Number(this.filterParams.minAmount) : 0) : null,
            zdhj: this.applyFilter ? (this.filterParams.maxAmount ? Number(this.filterParams.maxAmount) : Infinity) : null,
            applyFilter: this.applyFilter
          }),
          userInfo.aesKey,
          userInfo.aesIv
        );
        
        const res = await this.$myRequest.post_token(
          getApp().globalData.khkbInit,
          { data: enData + "" }
        );
        
        if (pageNum === 1) {
          this.$utils.hideLoading();
        }
        
        if (res.code === 200) {
          const decryptedData = JSON.parse(utils.decrypt(
            res.data,
            userInfo.aesKey,
            userInfo.aesIv
          ));
          
          const newData = decryptedData.khqfSummaryListInfo?.listInfo || [];
          
          if (pageNum === 1) {
            this.tableData = newData;
          } else {
            this.tableData = [...this.tableData, ...newData];
          }
          
          this.pageInfo = {
            total: decryptedData.khqfSummaryListInfo?.pageInfo?.total || 0,
            pageTotal: decryptedData.khqfSummaryListInfo?.pageInfo?.pageTotal || 0,
            pageSize: decryptedData.khqfSummaryListInfo?.pageInfo?.pageSize || 10
          };
          
          this.hasMoreData = pageNum < this.pageInfo.pageTotal;
          
          return Promise.resolve();
        } else {
          this.$utils.toast(`数据加载失败！错误码[${res.code}]`);
          return Promise.reject(new Error(`数据加载失败，错误码: ${res.code}`));
        }
      } catch (e) {  
        if (pageNum === 1) {
          this.$utils.hideLoading();
        }
        
        console.error("数据加载异常：", e);
        this.$utils.toast("数据加载失败！" + e.message);  
        return Promise.reject(e);         
      }
    },
    formatUnitName(name) {
      if (!name) return '';
      
      const prefixes = [
        "中国邮政集团有限公司武汉市",
        "中国邮政集团有限公司武汉",
        "中国邮政集团有限公司湖北",
        "中国邮政集团",
        "武汉市"
      ];
      
      let processedName = name;
      let hasChanged;
      
      do {
        hasChanged = false;
        for (const prefix of prefixes) {
          if (processedName.startsWith(prefix)) {
            processedName = processedName.replace(prefix, "").trim();
            hasChanged = true;
            break;
          }
        }
      } while (hasChanged);
      
      return processedName;
    },
    handleGoToDetail(item) {
      console.info("filterParams.customerName:"+this.filterParams.customerName); 	
      if (!item.khCode || !item.jg) {
        this.$utils.toast('参数缺失，无法跳转');
        return;
      }
      uni.navigateTo({
        url: `/pages/khkb/khkb_mx?customerName=${encodeURIComponent(this.filterParams.customerName)}&khCode=${encodeURIComponent(item.khCode)}&jg=${encodeURIComponent(item.jg)}`,
        fail: (err) => {
          console.error('跳转失败：', err);
        }
      });
    },
    handleBack() {
      uni.navigateBack({ delta: 1 });
    },
    setPresetAmount(amount) {
      this.filterParams.maxAmount = amount.toString();
      this.selectedAmount = amount;
    },
    // 点击"其它"弹出的输入框（模态框），其遮罩层默认会覆盖标题栏
    showOtherAmountInput() {
      // 保持筛选面板打开状态，不关闭
      uni.showModal({
        title: '请输入最大金额(元)',
        editable: true,
        placeholderText: '请输入金额',
        confirmText: '确认',
        cancelText: '取消',
        // 确保模态框层级高于标题栏（uni.showModal默认层级足够）
        success: (res) => {
          if (res.confirm) {
            const amount = Number(res.content);
            if (!isNaN(amount) && amount >= 0) {
              this.filterParams.maxAmount = amount.toString();
              this.selectedAmount = 'other';
            } else {
              this.$utils.toast('请输入有效的金额');
            }
          }
          // 无论确认还是取消，筛选面板都保持打开
        }
      });
    }
  }
};
</script>

<style scoped>
.container {
  width: 100%;
  height: 100vh;
  padding: 0;
  margin: 0;
  box-sizing: border-box;
  display: flex;
  flex-direction: column;
  overflow: hidden;
  background-color: #ffffff;
}

.main-content {
  flex: 1;
  width: 100%;
  box-sizing: border-box;
  display: flex;
  flex-direction: column;
  overflow: hidden;
  padding: 10px 0 0;
  background-color: #ffffff;
}

.search-container {
  background-color: #fff;
  padding: 15rpx 20rpx;
  margin-bottom: 10rpx;
  box-shadow: 0 2rpx 10rpx rgba(0,0,0,0.05);
  box-sizing: border-box;
}

.search-filter-row {
  display: flex;
  align-items: center;
  gap: 15rpx;
  width: 100%;
  box-sizing: border-box;
}

.search-box {
  flex: 1;
  display: flex;
  align-items: center;
  background-color: #f2f2f2;
  border-radius: 60rpx;
  padding: 10rpx 20rpx;
}

.search-icon {
  margin-right: 10rpx;
}

.search-input {
  flex: 1;
  height: 60rpx;
  font-size: 28rpx;
  color: #333;
  background-color: transparent;
  border: none;
  outline: none;
}

.filter-text-btn {
  display: flex;
  align-items: center;
  gap: 8rpx;
  color: #333;
  font-size: 28rpx;
  padding: 5rpx 10rpx;
  cursor: pointer;
}

.filter-icon {
  transition: transform 0.3s ease;
}

.rotate-up {
  transform: rotate(180deg);
}

/* 标题栏样式 - 基础层级，确保模态框能覆盖 */
.nav-bar {
  z-index: 100 !important;
}

/* 筛选面板 - 作为页面内元素，不使用遮罩和高层级 */
.filter-panel {
  margin-top: 15rpx;
  padding: 20rpx;
  background-color: #f9f9f9;
  border-radius: 8rpx;
  border: 1px solid #eee;
  animation: fadeIn 0.3s ease;
  box-sizing: border-box;
}

@keyframes fadeIn {
  from { opacity: 0; transform: translateY(-10rpx); }
  to { opacity: 1; transform: translateY(0); }
}

.filter-item {
  display: flex;
  align-items: center;
  width: 100%;
  margin-bottom: 20rpx;
}

.filter-label {
  font-size: 28rpx;
  color: #333;
  margin-right: 15rpx;
  white-space: nowrap;
}

.amount-range {
  display: flex;
  align-items: center;
  flex: 1;
  gap: 15rpx;
}

.amount-input {
  flex: 1;
  height: 60rpx;
  padding: 0 15rpx;
  font-size: 28rpx;
  color: #333;
  border: 1px solid #ddd;
  border-radius: 6rpx;
  outline: none;
  box-sizing: border-box;
}

.confirm-btn {
  background-color: #007aff;
  color: #fff;
  border: none;
  font-size: 26rpx;
  padding: 0 25rpx;
  height: 60rpx;
  border-radius: 6rpx;
  margin-left: 15rpx;
}

.amount-presets {
  display: flex;
  flex-wrap: wrap;
  gap: 15rpx;
  margin-top: 15rpx;
}

.preset-item {
  background-color: #fff;
  border: 1px solid #ddd;
  border-radius: 6rpx;
  padding: 10rpx 20rpx;
  font-size: 26rpx;
  color: #333;
  white-space: nowrap;
  cursor: pointer;
  transition: all 0.2s ease;
}

/* 预设金额选项默认颜色（未选中） */
.preset-item {
  background-color: #f5f5f5;
  border-color: #ddd;
  color: #666;
}

/* 选中状态颜色 */
.preset-item.selected {
  background-color: #007aff;
  color: #fff;
  border-color: #007aff;
}

.preset-item.other-item {
  color: #007aff;
  border-color: #007aff;
  background-color: #fff;
}

.preset-item.other-item.selected {
  background-color: #007aff;
  color: #fff;
}

.table-scroll-container {
  width: 100%;
  overflow-x: auto;
  overflow-y: auto;
  -webkit-overflow-scrolling: touch;
  background-color: #ffffff;
  touch-action: manipulation;
  flex: 1;
}

.data-table {
  box-sizing: border-box;
  border-collapse: collapse;
  position: relative;
}

.table-header {
  display: flex;
  background-color: #f8f8f8;
  color: #333;
  height: 45px;
  border-bottom: 1px solid #eee;
  align-items: center;
}

.table-header-fixed {
  position: sticky;
  top: 0;
  z-index: 90 !important; /* 低于标题栏，不冲突 */
}

.header-content {
  display: flex;
  width: 100%;
  height: 100%;
  padding-left: 10px;
  align-items: center;
  gap: 3px;
}

.header-text {
  flex: 1;
  text-align: left;
  line-height: 1;
  white-space: nowrap;
  font-weight: bold;
  color: #000;
  font-size: 13px;
}

.cell-content-center .header-text {
  text-align: center;
}

.sort-icon-container {
  width: 18px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.sort-icon-group {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 0;
}

.sort-icon {
  font-size: 9px;
  line-height: 1;
}

.table-body {
  display: flex;
  flex-direction: column;
}

.table-row {
  display: flex;
  width: 100%;
  height: 75px;
  border-bottom: 1px solid #eee;
  align-items: center;
}

.row-even {
  background-color: #ffffff;
}

.row-odd {
  background-color: #fef5f6;
}

.table-cell {
  padding: 8px 8px;
  text-align: left;
  font-size: 13px;
  border-right: 1px solid #eee;
  display: flex;
  align-items: center;
  box-sizing: border-box;
  white-space: normal;
  word-break: break-all;
  height: 100%;
  overflow: hidden;
}

.table-cell:last-child {
  border-right: none;
}

.cell-city {
  width: 130px !important;
  padding-left: 10px;
  position: relative;
  z-index: 80;
}

.table-col-fixed-1 {
  position: sticky !important;
  left: 0 !important;
  z-index: 85 !important;
  background-color: #f8f8f8 !important;
  border-right: 1px solid #eee !important;
  box-sizing: border-box !important;
  overflow: hidden !important;
  flex-shrink: 0 !important;
  flex-grow: 0 !important;
}

.row-even .table-col-fixed-1 {
  background-color: #ffffff !important;
}
.row-odd .table-col-fixed-1 {
  background-color: #fef5f6 !important;
}

.cell-data {
  min-width: 0;
}

.cell-content-center {
  justify-content: center;
  text-align: center;
}

.slide-column {
  position: relative;
}

.customer-name-link {
  color: red !important;
  text-decoration: underline;
  text-underline-offset: 2px;
  cursor: pointer;
  white-space: normal;
  word-break: break-all;
  display: inline-block;
  width: 100%;
  line-height: 1.3;
}

.pagination-info {
  height: 50px;
  line-height: 50px;
  font-size: 13px;
  color: #666;
  text-align: center;
  border-top: 1px solid #eee;
  background-color: #f9f9f9;
  margin: 0;
  padding: 0 15px;
  box-sizing: border-box;
  flex-shrink: 0;
}

.loading-tip {
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 15px 0;
  color: #666;
  font-size: 14px;
  text-align: center;
  width: 100%;
  box-sizing: border-box;
  transition: opacity 0.5s ease;
}

.loading-tip.fadeOut {
  opacity: 0;
}

.loading-text {
  margin-left: 8px;
}

.table-scroll-container::-webkit-scrollbar {
  width: 6px;
  height: 6px;
}

.table-scroll-container::-webkit-scrollbar-thumb {
  background-color: #ddd;
  border-radius: 3px;
}

.overdue-column {
  overflow: hidden;
  padding: 8px 5px;
}

.overdue-text {
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  max-width: 100%;
}
</style>